package com.wz.utils.batch.mapper;


import com.wz.utils.batch.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void batchUpdate(List<User> userList){
        List<Object[]> collect = userList.stream().map(item -> new Object[]{item.getId(), item.getUserName(), item.getDateTime()}).collect(Collectors.toList());
        Connection conn = null;
        try {
            conn = jdbcTemplate.getDataSource().getConnection();
            conn.setAutoCommit(false);
            jdbcTemplate.batchUpdate("insert into user values(?,?,?)",collect);
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }
}
